﻿/*  
 *  IIS LogFile Analyser, Copyright (C) 2013. http://www.iis-analyser.com
 *  --
 *  This program is free software, provided "AS IS" WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
 * 
 *  File Author: Ian Quigley,    2013-02-23
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LogParser;
using DataStore;
using LogParser.DTO;
using System.IO;

namespace AppLogic
{
    public class Processor
    {
        private SiteRecord _site;
        private Store _store;

        public Processor(Store store, SiteRecord site)
        {
            _store = store;
            _site = site;
        }

        public bool AddUpdateFile(string filePath)
        {
            LogFileParser parser= null;
            bool isError = false;

            try
            {
                parser = new LogFileParser( filePath );
                
                var fileRecord = _store.FindOrCreateFile( _site, filePath );
                
                long lineCount = fileRecord.LinesRead;

                if (!parser.SkipLines( lineCount ))
                    return false;

                while (!parser.IsEmpty)
                {
                    var read = parser.Read();
                    if (isError = read.IsError)
                        break;

                    lineCount++;

                    if (read is LineDocument)
                    {
                        var line = (LineDocument)read;

                        var visit = Mapper.LineDocumentVisitRecord.From( line, _store, fileRecord, _site );
                        visit.Save();
                    }
                }

                FileInfo info = new FileInfo( filePath );
                fileRecord.SizeBytes = info.Length;
                fileRecord.Updated = info.LastWriteTimeUtc;
                fileRecord.FileDate = parser.DocumentHeader.Updated;
                fileRecord.LinesRead = lineCount;
                fileRecord.Save();                
            }
            finally
            {   
                if (parser != null)
                    parser.Dispose();
            }

            return isError;
        }
    }
}
